import json

from django.shortcuts import render
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import serializers
from rest_framework.views import APIView
from drf_yasg.utils import swagger_auto_schema
from rest_framework.parsers import FormParser
from rest_framework.decorators import parser_classes, permission_classes
from drf_yasg import openapi
from dvadmin.utils.serializers import CustomModelSerializer
from dvadmin.utils.json_response import DetailResponse, ErrorResponse
from dvadmin.utils.viewset import CustomModelViewSet
import process.algorithms as algorithms
import base64
import json
import os
import cv2
import requests
from django.http import HttpResponse
from datasource.camera import CameraFactory, BaseCamera
from datasource.minio_config import minioClient
from django.http import StreamingHttpResponse, Http404, JsonResponse
from django.core.files.uploadedfile import InMemoryUploadedFile, TemporaryUploadedFile


# @swagger_auto_schema(
#     method='post',
#     request_body=openapi.Schema(
#         type=openapi.TYPE_OBJECT,
#         required=['img','operations'],
#         properties={
#             'img': openapi.Schema(type=openapi.TYPE_FILE),
#             'operations': openapi.Schema(type=openapi.TYPE_OBJECT)
#         },
#     ),
#     operation_description='Create an events'
# )
@api_view(["POST"])
@permission_classes([])
def applyOperations(request):
    if request.method == "POST":
        img = request.data["img"]
        operations = request.data["operations"]
        img = algorithms.bin2CV(img)
        data = []
        for opr in operations:
            img, d = algorithms.OPERATIONS[opr['name']](img=img, **opr['params'])
            data.append(d)
        return DetailResponse(data=data)


def getChatGptProcess(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body.decode('utf-8'))
            question = data.get('question', '')

            result = send_chat_gpt_request(question)

            response_data = {
                "code": 2000,
                "msg": "success",
                "data": {
                    "result": result  # 将实际结果放入data字段
                }
            }

            return JsonResponse(response_data)

        except Exception as e:
            return JsonResponse({
                "code": 5000,
                "msg": f"Server error: {str(e)}",
                "data": {}
            }, status=500)

    else:
        return JsonResponse({
            "code": 4000,
            "msg": "Invalid request method",
            "data": {}
        }, status=405)


def send_chat_gpt_request(question):
    question = "可使用的基础操作有：通道变更，裁剪，缩放，旋转，阈值化，滤波，去噪，形态学，边缘检测，轮廓检测，霍夫变换，特征检测，透视变换，像素统计，ai算子，ocr识别，读取参数。你在给出的基础操作中选择必要的基础操作，按照顺序写出"+question+"算法的流程，列出名称就行，不需要解释具体操作。"
    url = 'https://api.siliconflow.cn/v1/chat/completions'
    headers = {
        'Authorization': 'Bearer sk-fuuclzwyvhlahmlucmzlwpjoiehbxjwtdhxlhiwcvereovgt',
        'Content-Type': 'application/json'
    }
    data = {
        "model": "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B",
        "stream": False,
        "max_tokens": 9000,
        "temperature": 0.7,
        "top_p": 0.7,
        "top_k": 50,
        "frequency_penalty": 0.5,
        "n": 1,
        "messages": [
            {
                "content": question,
                "role": "user"
            }
        ]
    }
    response = requests.post(url, headers=headers, data=json.dumps(data))

    if response.status_code == 200:
        answer = response.json()

        chat_gpt_answer = answer.get('choices', [{}])[0].get('message', '').get('content', '')
        print(chat_gpt_answer)
        return {
            "data": chat_gpt_answer,
        }
    else:
        print(f"Error: {response.status_code}, {response.text}")
        return {"error": "Failed to retrieve chat GPT response"}
